import { getUserInfo, login, updatePassword } from '@/api/user'
import { getToken, removeToken, setToken } from '@/utils/auth'

const getDefaultState = () => {
  return {
    token: getToken(),
    userInfo: [],
    avatar: ''
  }
}

const state = getDefaultState()

const mutations = {
  setToken(state, token) {
    state.token = token
  },
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
    // console.log(userInfo)
  },
  removeToken(state) {
    state.token = null
    removeToken()
  }
}

const actions = {
  // user login
  async login({ commit }, userInfo) {
    // todo: 调用登录接口
    const { mobile, passWord } = userInfo
    await login({ mobile: mobile.trim(), password: passWord }).then(response => {
      const { data } = response
      console.log(data)
      commit('setToken', data)
      setToken(data)
    })
  },

  // 获取用户信息
  async getUserInfo({ commit }) {
    await getUserInfo().then(response => {
      const result = response.data
      // console.log(result)
      commit('setUserInfo', result)
    })
  },
  // 退出
  async logout(context) {
    context.commit('removeToken') // 删除token
    context.commit('setUserInfo', {})
  },
  async updatePassword({ commit }, data) {
    // console.log(data)
    await updatePassword(data).then(response => {
      // const { success } = response.data
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

